<script setup lang="ts">
import Main from './components/Main.vue'
import Tabs from './components/Tabs.vue'

const { t } = useI18n()
const router = useRouter()
definePageMeta({
    layout: 'header-back',
    title: 'interest_treasure'
})
const tabsList = [
    { title: '存款', value: 0 },
    { title: '取款', value: 1 },
]
const tabsActive = ref(0)

const activeCurrency = ref<CurrencyData>()

const activeTab = ref('deposit')
const tabOptions = [
  { label: t('deposit'), value: 'deposit' },
  { label: t('menu_title_settings_withdrawals'), value: 'withdraw' },
]
const amountRef = ref()
const password = ref('')
const passwordRef = ref()
const _curGlobalCurrency = computed(() => isLogin.value ? currentGlobalCurrency.value : appStore.getLanguageCurrency())
const maxAmount = ref('0.00')

// 获取利率
const { data: interestConfig, runAsync: runAsyncInterestConfig } = useRequest(ApiMemberInterestConfig, {
  debounceInterval: 1000,
  debounceOptions: {
    leading: true,
    trailing: false,
  },
})

const { getComponent } = useUserVerify()
const {
  value: amount,
  errorMessage: errAmount,
  resetField: resetAmount,
  validate: validateAmount,
  setValue: setAmount,
} = useField<string>('amount', (value) => {
  if (!isLogin.value)
    return ''
  if (!value)
    return t('min_amount_0')
  else if (Number(value) <= 0)
    return t('min_amount_0')
  else if (activeCurrency.value && Number(value) > Number(activeCurrency.value?.balance))
    maxNumber()
    // return t('validate_deposit_amount_max')
  return ''
})

const currency_code = computed(() => (getCurrencyConfig(_curGlobalCurrency.value)).cur)
const isDeposit = computed(() => activeTab.value === 'deposit')
const updateType = computed(() => isDeposit.value ? 1 : 2)
const updateParams = computed<IMemberBalanceLockerUpdate | null>(() => {
  if (activeCurrency.value) {
    return {
      amount: amount.value,
      flag: updateType.value,
      currency_id: Number(activeCurrency.value.cur),
      device: 0,
    }
  }
  return null
})
// 当前币种配置
const vaultFig = computed(() => {
  return interestConfig.value ? interestConfig.value.rate : { interest_rate: 0, min_deposit: 0, bill_time: 0 }
})

const billTime = computed(() => {
  if (vaultFig.value && vaultFig.value.bill_time) {
    const _billTime = +(vaultFig.value.bill_time || 0) // 秒
    const hour = Math.floor(_billTime / 60 / 60)
    const day = Math.floor(hour / 24)

    if (hour < 24) {
      if (hour <= 1)
        return t('time_hour')
      else
        return t('time_hour', { delta: hour })
    }
    if (day <= 1)
      return t('quantos_dias')
    else
      return t('quantos_dias', { delta: day })
  }

  return 0
})

function renderSvg(text: string) {
  return `<svg aria-hidden="true" style="width:14px;height:14px;margin: 0 5px;">
          <use xlink:href="#icon-coin-${text}"/>
        </svg>`
}
const {
  run: runLockerUpdate,
  loading: lockerUpdateLoading,
} = useRequest(ApiMemberBalanceLockerUpdate, {
  ready: isLogin,
  async onSuccess() {
    openNotify({
      title: isDeposit.value
        ? t('finance_other_tab_vault_deposit')
        : t('finance_other_tab_vault_withdrawal'),
      icon: 'navbar-wallet-notify',
      message: isDeposit.value
        ? t('success_deposit',
          {
            amount: updateParams.value?.amount,
            icon: activeCurrency.value ? renderSvg(activeCurrency.value.type.toLocaleLowerCase()) : '',
          })
        : t('confirm_draw_vault', {
          amount: updateParams.value?.amount,
          icon: activeCurrency.value ? renderSvg(activeCurrency.value.type.toLocaleLowerCase()) : '',
        }),
    })
    reset()
    appStore.getBalanceData()
    appStore.getLockerData()
    passwordRef.value?.resetPassword()
  },
})

async function handleUpdate() {
  if (!isLogin.value) {
    openRegisterDialog()
    return
  }
  amountRef.value.setTouchTrue()
  if (passwordRef.value)
    passwordRef.value.setTouchTrue()
  await validateAmount()
  if (isDeposit.value) {
    if (!errAmount.value && updateParams.value) {
      if (Number(amount.value) < Number(vaultFig.value?.min_deposit ?? 0)) {
        openNotify({
          title: t('finance_other_tab_vault_deposit'),
          type: 'error',
          message: t('currency_min_deposit_amount', { amount: vaultFig.value?.min_deposit, icon: activeCurrency.value ? renderSvg(activeCurrency.value.type.toLocaleLowerCase()) : '' }),
        })
      }
      else {
        runLockerUpdate(updateParams.value)
      }
    }
  }
  else {
    await passwordRef.value.validatePassword()
    if (!errAmount.value && !passwordRef.value.errPassword && updateParams.value)
      runLockerUpdate({ ...updateParams.value, password: password.value, auth_type: +passwordRef.value.authType })
  }
}
function changeCurrency(item: CurrencyData) {
  const config = getCurrencyConfig(_curGlobalCurrency.value)
  item = item ?? { type: _curGlobalCurrency.value, balance: '0.00', balanceWithSymbol: '0.00', cur: config.cur, prefix: config.prefix } as CurrencyData
  runAsyncInterestConfig({ cur: item?.cur ?? currency_code.value })
  activeCurrency.value = item

  reset()
  emits('change', item)
}
function maxNumber() {
  if (!isLogin.value)
    return
  if (activeCurrency.value && isDeposit.value)
    setAmount(application.formatNumDecimal(activeCurrency.value.balance, currencyConfig[activeCurrency.value.type].decimal))

  else if (activeCurrency.value && !isDeposit.value)
    setAmount(application.formatNumDecimal(activeCurrency.value.balance, currencyConfig[activeCurrency.value.type].decimal))

  else setAmount(application.formatNumDecimal(0, 2))
}
function reset() {
  resetAmount()
  if (activeCurrency.value) {
    maxAmount.value = application.formatNumDecimal(activeCurrency.value.balance, currencyConfig[activeCurrency.value.type].decimal)
    setAmount(application.formatNumDecimal(0, currencyConfig[activeCurrency.value.type].decimal), false)
  }
}
function handleBlur() {
  if (activeCurrency.value)
    setAmount(application.formatNumDecimal(amount.value, currencyConfig[activeCurrency.value.type].decimal), true)
}
function handleTabChange(tab: string) {
  if (tab === 'deposit')
    reset()
  else
    nextTick(maxNumber)
}

function getCurrencyMaxBalance() {
  const now_currencyData = renderBalanceList.value.find(item => _curGlobalCurrency.value === item.type)
  if (now_currencyData)
    maxAmount.value = application.formatNumDecimal(now_currencyData.balance, currencyConfig[now_currencyData.type].decimal)
}

watch(() => activeTab.value, () => {
  amountRef.value?.setTouchFalse()
})

watch(() => _curGlobalCurrency.value, (val) => {
  const code = getCurrencyConfig(val).cur
  runAsyncInterestConfig({ cur: code })
})

watch(isLogin, (val) => {
  amountRef.value?.setTouchFalse()
  if (val) {
    // changeCurrency(activeCurrency.value)
    appStore.getBalanceData().then(() => {
      appStore.getLockerData().then(() => {
        runAsyncInterestConfig({ cur: currency_code.value })
        maxNumber()
      })
    })
    setTimeout(() => {
      maxNumber()
    }, 2000)
  }
})

onMounted(() => {
    runAsyncInterestConfig({ cur: currency_code.value })
  getCurrencyMaxBalance()
})

</script>


<template>
    <div>
        <div>
            <Tabs
                v-model:active="tabsActive" :list="tabsList"
                :style="{ '--tabs-width': '50%', '--tabs-indicator-position': `${tabsActive * 100}%` }" />
            <div class="top-wrapper pt-10 pb-6 px-4">
                <div class="flex justify-center mb-4">
                    <BaseImage url="/images/png/wallet/vault/banner.png" class="w-[80%]" />
                </div>
                <Main :tabsActive="tabsActive" />
            </div>

        </div>
    </div>


</template>

<style scoped lang="scss">
.top-wrapper {
    background: linear-gradient(0deg, rgba(74, 3, 255, 0.00) 27.13%, rgba(74, 3, 255, 0.30) 86.48%);
}
</style>